package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartcampusbackend.mapper.RepairApplicationMapper;
import com.smartcampusbackend.mapper.RepairStatusLogMapper;
import com.smartcampusbackend.model.RepairApplication;
import com.smartcampusbackend.model.RepairStatusLog;
import com.smartcampusbackend.service.RepairApplicationService;
import com.smartcampusbackend.util.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class RepairApplicationServiceImpl extends ServiceImpl<RepairApplicationMapper, RepairApplication> implements RepairApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(RepairApplicationServiceImpl.class);

    @Autowired
    private RepairApplicationMapper repairApplicationMapper;

    @Autowired
    private RepairStatusLogMapper repairStatusLogMapper;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Override
    @Transactional
    public boolean submitApplication(RepairApplication application, List<MultipartFile> photos) {
        try {
            // 生成申请编号
            application.setApplicationNo(generateApplicationNo());
            application.setStatus("待审批");
            application.setCreateTime(LocalDateTime.now());
            application.setUpdateTime(LocalDateTime.now());

            // 处理照片上传
            if (photos != null && !photos.isEmpty()) {
                List<String> photoUrls = new ArrayList<>();
                for (MultipartFile photo : photos) {
                    if (photo != null && !photo.isEmpty()) {
                        // 检查文件大小（5MB限制）
                        if (photo.getSize() > 5 * 1024 * 1024) {
                            logger.error("照片文件大小超过5MB限制: {}", photo.getOriginalFilename());
                            return false;
                        }
                        
                        // 检查文件类型
                        String contentType = photo.getContentType();
                        if (contentType == null || !contentType.startsWith("image/")) {
                            logger.error("不支持的文件类型: {}", contentType);
                            return false;
                        }

                        // 上传文件
                        String fileUrl = fileUploadUtil.uploadImage(photo, "repair-photos");
                        if (fileUrl != null) {
                            photoUrls.add(fileUrl);
                        }
                    }
                }
                application.setPhotoUrls(String.join(",", photoUrls));
            }

            // 保存申请
            boolean result = save(application);
            
            if (result) {
                // 记录状态变更日志
                RepairStatusLog statusLog = new RepairStatusLog();
                statusLog.setApplicationId(application.getId());
                statusLog.setFromStatus(null);
                statusLog.setToStatus("待审批");
                statusLog.setOperatorId(application.getApplicantId());
                statusLog.setOperatorName(application.getApplicantName());
                statusLog.setOperatorRole(application.getApplicantRole());
                statusLog.setOperationTime(LocalDateTime.now());
                statusLog.setRemark("提交维修申请");
                repairStatusLogMapper.insert(statusLog);
            }

            return result;
        } catch (Exception e) {
            logger.error("提交维修申请失败", e);
            return false;
        }
    }

    @Override
    public List<RepairApplication> getUserApplications(Integer userId) {
        return repairApplicationMapper.selectByApplicantId(userId);
    }

    @Override
    public List<RepairApplication> getAssigneeApplications(Integer assigneeId) {
        return repairApplicationMapper.selectByAssigneeId(assigneeId);
    }

    @Override
    public List<RepairApplication> getAllApplications() {
        return repairApplicationMapper.selectAllApplications();
    }

    @Override
    public List<RepairApplication> getApplicationsByStatus(String status) {
        return repairApplicationMapper.selectByStatus(status);
    }

    @Override
    public RepairApplication getApplicationById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional
    public boolean assignRepairman(Long applicationId, Integer assigneeId, String assigneeName) {
        try {
            RepairApplication application = getById(applicationId);
            if (application == null) {
                return false;
            }

            application.setAssigneeId(assigneeId);
            application.setAssigneeName(assigneeName);
            application.setStatus("已分配");
            application.setAssignTime(LocalDateTime.now());
            application.setUpdateTime(LocalDateTime.now());

            boolean result = updateById(application);
            
            if (result) {
                // 记录状态变更日志
                RepairStatusLog statusLog = new RepairStatusLog();
                statusLog.setApplicationId(applicationId);
                statusLog.setFromStatus("待审批");
                statusLog.setToStatus("已分配");
                statusLog.setOperatorId(assigneeId);
                statusLog.setOperatorName(assigneeName);
                statusLog.setOperatorRole("STAFF");
                statusLog.setOperationTime(LocalDateTime.now());
                statusLog.setRemark("分配给维修人员：" + assigneeName);
                repairStatusLogMapper.insert(statusLog);
            }

            return result;
        } catch (Exception e) {
            logger.error("分配维修人员失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean startRepair(Long applicationId, Integer operatorId, String operatorName) {
        try {
            RepairApplication application = getById(applicationId);
            if (application == null) {
                return false;
            }

            application.setStatus("维修中");
            application.setStartTime(LocalDateTime.now());
            application.setUpdateTime(LocalDateTime.now());

            boolean result = updateById(application);
            
            if (result) {
                // 记录状态变更日志
                RepairStatusLog statusLog = new RepairStatusLog();
                statusLog.setApplicationId(applicationId);
                statusLog.setFromStatus("已分配");
                statusLog.setToStatus("维修中");
                statusLog.setOperatorId(operatorId);
                statusLog.setOperatorName(operatorName);
                statusLog.setOperatorRole("STAFF");
                statusLog.setOperationTime(LocalDateTime.now());
                statusLog.setRemark("开始维修");
                repairStatusLogMapper.insert(statusLog);
            }

            return result;
        } catch (Exception e) {
            logger.error("开始维修失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean completeRepair(Long applicationId, Integer operatorId, String operatorName, String actualDuration) {
        try {
            RepairApplication application = getById(applicationId);
            if (application == null) {
                return false;
            }

            application.setStatus("完成");
            application.setCompleteTime(LocalDateTime.now());
            application.setActualDuration(actualDuration);
            application.setUpdateTime(LocalDateTime.now());

            boolean result = updateById(application);
            
            if (result) {
                // 记录状态变更日志
                RepairStatusLog statusLog = new RepairStatusLog();
                statusLog.setApplicationId(applicationId);
                statusLog.setFromStatus("维修中");
                statusLog.setToStatus("完成");
                statusLog.setOperatorId(operatorId);
                statusLog.setOperatorName(operatorName);
                statusLog.setOperatorRole("STAFF");
                statusLog.setOperationTime(LocalDateTime.now());
                statusLog.setRemark("维修完成，实际用时：" + actualDuration);
                repairStatusLogMapper.insert(statusLog);
            }

            return result;
        } catch (Exception e) {
            logger.error("完成维修失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean cancelApplication(Long applicationId, Integer operatorId, String operatorName, String cancelReason) {
        try {
            RepairApplication application = getById(applicationId);
            if (application == null) {
                return false;
            }

            application.setStatus("已取消");
            application.setCancelTime(LocalDateTime.now());
            application.setCancelReason(cancelReason);
            application.setUpdateTime(LocalDateTime.now());

            boolean result = updateById(application);
            
            if (result) {
                // 记录状态变更日志
                RepairStatusLog statusLog = new RepairStatusLog();
                statusLog.setApplicationId(applicationId);
                statusLog.setFromStatus(application.getStatus());
                statusLog.setToStatus("已取消");
                statusLog.setOperatorId(operatorId);
                statusLog.setOperatorName(operatorName);
                statusLog.setOperatorRole("STAFF");
                statusLog.setOperationTime(LocalDateTime.now());
                statusLog.setRemark("取消申请，原因：" + cancelReason);
                repairStatusLogMapper.insert(statusLog);
            }

            return result;
        } catch (Exception e) {
            logger.error("取消申请失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateApplication(RepairApplication application, List<MultipartFile> photos) {
        try {
            // 处理新的照片上传
            if (photos != null && !photos.isEmpty()) {
                List<String> photoUrls = new ArrayList<>();
                
                // 保留原有照片
                if (application.getPhotoUrls() != null && !application.getPhotoUrls().isEmpty()) {
                    String[] existingPhotos = application.getPhotoUrls().split(",");
                    for (String photo : existingPhotos) {
                        if (photo != null && !photo.trim().isEmpty()) {
                            photoUrls.add(photo.trim());
                        }
                    }
                }
                
                // 添加新照片
                for (MultipartFile photo : photos) {
                    if (photo != null && !photo.isEmpty()) {
                        // 检查文件大小（5MB限制）
                        if (photo.getSize() > 5 * 1024 * 1024) {
                            logger.error("照片文件大小超过5MB限制: {}", photo.getOriginalFilename());
                            return false;
                        }
                        
                        // 检查文件类型
                        String contentType = photo.getContentType();
                        if (contentType == null || !contentType.startsWith("image/")) {
                            logger.error("不支持的文件类型: {}", contentType);
                            return false;
                        }

                        // 上传文件
                        String fileUrl = fileUploadUtil.uploadImage(photo, "repair-photos");
                        if (fileUrl != null) {
                            photoUrls.add(fileUrl);
                        }
                    }
                }
                application.setPhotoUrls(String.join(",", photoUrls));
            }

            application.setUpdateTime(LocalDateTime.now());
            return updateById(application);
        } catch (Exception e) {
            logger.error("更新维修申请失败", e);
            return false;
        }
    }

    @Override
    public List<RepairStatusLog> getStatusLogs(Long applicationId) {
        return repairStatusLogMapper.selectByApplicationId(applicationId);
    }

    @Override
    public Map<String, Object> getStatistics() {
        return repairApplicationMapper.selectStatistics();
    }

    @Override
    public String generateApplicationNo() {
        String prefix = "RP";
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String sequence = String.format("%03d", (int) (Math.random() * 1000));
        return prefix + date + sequence;
    }

    @Override
    public List<RepairApplication> exportApplications(String status, String type, String priority, String keyword) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<RepairApplication> wrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        if (status != null && !status.isEmpty()) wrapper.eq("status", status);
        if (type != null && !type.isEmpty()) wrapper.eq("repair_type", type);
        if (priority != null && !priority.isEmpty()) wrapper.eq("priority", priority);
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w.like("description", keyword).or().like("location", keyword));
        }
        return this.list(wrapper);
    }
} 